# -*- coding: utf-8 -*-
"""
Created on Sat Sep 19 16:16:45 2020

@author: Administrator
"""

'''
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:

Input:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
'''

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        res =[]
        '''
        20200919-李运辰
        模仿 59. Spiral Matrix II解法
        '''
        if len(matrix)==0:
            return []
        hang = len(matrix)
        lie = len(matrix[0])
        
        value=1
        rows,columns,xlimit,ylimit,size=0,0,0,0,hang*lie
        
        
        while(value<=(size)):
            #第一行
            while(columns<lie):#columns
                res.append(matrix[rows][columns])
                value+=1
                columns+=1

            #最后一列
            columns-=1
            rows+=1
            while(rows<hang):
                res.append(matrix[rows][columns])
                value+=1
                rows+=1


            columns-=1
            rows-=1

            while(columns>=ylimit):
                res.append(matrix[rows][columns])
                value+=1
                columns-=1
            rows-=1
            columns+=1

            while(rows>xlimit):
                res.append(matrix[rows][columns])
                value+=1
                rows-=1
                
            rows+=1
            columns+=1
            hang -=1
            lie -=1
            xlimit+=1
            ylimit+=1
         
        if len(res)>size:
            res =res[0:size]
        return res
        